package utils;

import org.apache.commons.io.IOUtils;
import play.Logger;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * CSV工具
 * @author zhangzc
 * @since 2017/7/21
 */
public class CsvUtil {

    /**
     * 导出
     *
     * @param file     csv文件，csv文件不存在会自动创建
     * @param dataList 数据
     * @return
     */
    public static boolean exportCsv(File file, List<String> dataList) {
        FileOutputStream out = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(file);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            if (dataList != null && !dataList.isEmpty()) {
                for (String data : dataList) {
                    bw.append(data).append('\r');
                }
            }
            return true;
        } catch (Exception e) {
            Logger.error(e, "Error in exportCsv");
            return false;
        } finally {
            IOUtils.closeQuietly(bw);
            IOUtils.closeQuietly(osw);
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 导入
     *
     * @param file csv文件
     * @return
     */
    public static List<String> importCsv(File file) {
        List<String> dataList = new LinkedList<>();

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                dataList.add(line);
            }
        } catch (Exception e) {
            Logger.error(e, "Error in importCsv");
        } finally {
            IOUtils.closeQuietly(br);
        }

        return dataList;
    }
}
